package org.wendu.wdoa.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.wendu.wdoa.common.CurrentUser;
import org.wendu.wdoa.common.OaConstants;
import org.wendu.wdoa.common.Result;
import org.wendu.wdoa.common.token.TokenUser;
import org.wendu.wdoa.common.token.TokenUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//令牌认证过滤器
public class TokenVerifyFilter extends BasicAuthenticationFilter {
    public TokenVerifyFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public TokenVerifyFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        try {
            //从请求头中获取令牌
            String clientToken = request.getHeader(OaConstants.HEADER_NAME_TOKEN);
            TokenUser tokenUser = TokenUtils.verify(clientToken);

            //验证通过，自定义认证信息（永远都放行）

            CurrentUser principal = new CurrentUser(clientToken,null,clientToken);//创建当事人
            String credentials = clientToken;
            //创建认证信息
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken( principal,credentials);

            //将认证信息放入SpringSecurity的安全上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);

            chain.doFilter(request,response);//进行后续处理

        } catch (Exception e) {

            Result error = Result.err(Result.CODE_ERR_UNLOGINED, e.getMessage());
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(error);

            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(jsonStr);
            out.flush();
            out.close();


        }


    }
}
